import type {UseFetchOptions} from "nuxt/app";

const useServerRequest = <T>(url: string, opts?: UseFetchOptions<T, unknown>) => {
  const defaultOptions: UseFetchOptions<unknown> = {
    baseURL: '',
    // onRequest({ options }) {
    //   options.headers = (options.headers || {}) as { [key: string]: string }
    // },
    // onResponse({ response }) {
    //   if (+response.status === 200 && +response._data.code !== 200) {
    //     process.client && ElMessage.error(response._data.msg)
    //   }
    // },
    // onResponseError({ response }) {
    //   process.client && ElMessage.error(response._data.data)
    // }
  }
  return new Promise((resolve, reject)=>{
    useFetch<T>( url, {...defaultOptions, ...opts} as any)
      .then(({ data, error }: any) => {
        if (error.value) {
          console.log({
            message: "服务器内部错误",
            type: "error",
          });
          return reject(error.value);
        }
        const value = data.value;
        if (!value) {
          console.log("执行错误了");
          // 这里处理错误回调
          resolve(value)
          // $router.replace('/reject/' + value.status)
        } else if (value.code !== 200) {
          // navigateTo('/404',{replace:true})
          // return
          console.log({
            message: value.msg,
            type: "error",
          });
          resolve(value)
        } else {
          resolve(value);
        }
      })
      .catch((err: any) => {
        reject(err);
      });
  })
}

export default new (class HttpServer {
  get(url: string, params?: any): Promise<any> {
    return useServerRequest(url, { method: "get", params });
  }
  postParams(url: string, params?: any): Promise<any> {
    return useServerRequest(url, { method: "post", params });
  }
  post(url: string, body?: any): Promise<any> {
    return useServerRequest(url, { method: "post", body });
  }

  postFile(url: string, body?: any): Promise<any> {
    return useServerRequest(url, { method: "post", body });
  }

  put(url: string, body?: any): Promise<any> {
    return useServerRequest(url, { method: "put", body });
  }

  delete(url: string, body?: any): Promise<any> {
    return useServerRequest(url, { method: "delete", body });
  }
})();

